﻿using System.Xml;
using SharpObjects.Configuration.ConfigurationProviders;
using SharpObjects.RuleEngine.RuleElements;

namespace SharpObjects.RuleEngine.Rules
{
    public class IfLessThanRule : IRule
    {
        public FieldElement Field { get; set; }
        public FieldElement Threshold { get; set; }
        public ListOfRulesElement YesList { get; set; }
        public ListOfRulesElement NoList { get; set; }

        #region IInitializable Members

        public void Initialize(XmlElement initializationElement)
        {
            XmlConfigurationProvider init = new XmlConfigurationProvider(initializationElement);

            Field = init.GetObject<FieldElement>("field");
            Threshold = init.GetObject<FieldElement>("threshold");
            YesList = init.GetObject<ListOfRulesElement>("yes");
            NoList = init.GetObject<ListOfRulesElement>("no", (ListOfRulesElement) null);

            this.IsInitialized = true;
        }

        public bool IsInitialized { get; set; }

        #endregion

        #region IRule Members

        public void Execute(ref IRuleEngineContext ruleEngineContext, IDataProvider dataProvider)
        {
            if(this.Field.IsLessThan(this.Threshold, ruleEngineContext, dataProvider))
            {
                foreach(IRule rule in YesList.Rules)
                {
                    rule.Execute(ref ruleEngineContext, dataProvider);
                }
            }
            else
            {
                foreach (IRule rule in NoList.Rules)
                {
                    rule.Execute(ref ruleEngineContext, dataProvider);
                }
            }
        }

        #endregion
    }
}
